package ferp.center.server.servlet.bid;

import ferp.center.network.request.RequestBidAdd;
import ferp.center.server.Action;
import ferp.center.server.entity.Bid;
import ferp.core.game.Settings;
import ferp.core.util.Convert;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: igorgok
 * Date: 12/5/12 9:47 AM
 */
public class BidAdd extends HttpServlet
{
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, RequestBidAdd.class, new Action.Write<RequestBidAdd, Boolean>()
    {
      @SuppressWarnings("unchecked")
      public Boolean run(EntityManager em, RequestBidAdd input) throws IOException
      {
        // do not look for Profile object, save reads
        // only for new configuration codes (5 character long and more) and expert/expert opponent levels
        if (input.configuration.length() >= 5 &&
            input.configuration.charAt(3) == EXPERT && input.configuration.charAt(4) == EXPERT &&
            // do not count PP_1248 configuration
            input.configuration.charAt(1) != GEOMETRIC)
        {
          input.configuration = Convert.configuration(input.configuration);

          Bid bid = new Bid(input);

          em.persist(bid);

          return Boolean.TRUE;
        }

        return Boolean.FALSE;
      }
    });
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {

  }

  private static final char GEOMETRIC = String.valueOf(Settings.PassingProgression.PP_1248.ordinal()).charAt(0);
  private static final char EXPERT = String.valueOf(Settings.Level.L0.ordinal()).charAt(0);
}
